package com.ceba.be.api.utils;

import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.util.URIUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 根据URL下载网络中的文件，并写入本地磁盘
 */
public class DownLoadSignTest {

	public static void main(String[]args) throws URIException {
		downloadFile("http://localhost:8080/ep/fileVisit/55555555555555555555555555555555/upfile/sign/2020-03-12/%E4%B8%AA%E4%BA%BA%E9%80%9A%E7%94%A8%E8%AF%81%E4%B9%A6%E7%94%B3%E8%AF%B7%E8%A1%A8_202003122102049583975544697_sign.pdf","C:\\Users\\liguangyao\\Desktop\\个人通用证书申请表_rsa.pdf");
	}

	public static void downloadFile(String remoteFilePath, String localFilePath)
    {
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(localFilePath);
        try
        {
            //将URL中的中文urlencode
            remoteFilePath = URIUtil.encodeQuery(remoteFilePath);
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection)urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1)
            {
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bis.close();
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
   
}
